package com.ydd.controller.user;

import com.ydd.exception.BaseException;
import com.ydd.result.Result;
import com.ydd.utils.AliOssUtil;
import com.ydd.vo.UploadVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Description TODO
 * @Author itheima
 * @Date 2023-05-04 9:59
 */
@Api(tags = "文件上传")
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     *
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<UploadVO> upload(@RequestParam("file") MultipartFile file) {
        try {
            log.info("文件上传:{}", file);
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //获取后缀名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //生成唯一标识名
            String fileName = UUID.randomUUID().toString().replace("-", "") + extension;

            String savePath = aliOssUtil.upload(file.getBytes(), fileName);


            UploadVO uploadVO = new UploadVO();
            uploadVO.setSavePath(savePath);
            uploadVO.setName(fileName);
            uploadVO.setMime(extension.substring(1));
            uploadVO.setSize(file.getBytes().length);

            return Result.success(uploadVO);


        } catch (IOException e) {
            throw new BaseException(e.getMessage());
        }
    }
}
